import Vue from 'vue'
import Router from 'vue-router'
import Login from './views/Login.vue'
import NotFound from './views/NotFound.vue'
Vue.use(Router)

const router =  new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    { path: '*', component: NotFound},
    { path: '/', 
      name:'home',
      component: () => import('./views/Home.vue'),
      redirect:{name:'welcome'},
      children:[
        {
          name:'welcome',
          path:'welcome',
          component:()=>import('./views/Welcome.vue')
        },
        {
          name:'user',
          path:'/user',
          component:()=>import('./views/User.vue')
        },
        {
          name:'rights',
          path:'/rights',
          component:()=>import('./views/Rights.vue')
        },
        {
          name:'roles',
          path:'/roles',
          component:()=>import('./views/Roles.vue')
        }
      ]
    },
  ]
})

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('mytoken')
  if (token) {
    next()//合法用户，放行
  } else {
    if (to.path == '/login') {
      //如果没有登录，但你访问的是login,直接放行
      next()
    } else {
      //否则跳转到login
      next({ path: '/login' })
    }
  }
})

export default router 